import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SystemManager {
        private UserManager userManager;
        private MovieManager movieManager;
        private SessionManager sessionManager;
        private TicketManager ticketManager;
        private Scanner scanner = new Scanner(System.in);
        private List<Hall> halls = new ArrayList<>();

    public SystemManager() {
            // 初始化影厅
            halls.add(new Hall("黄金厅", 8, 10));
            halls.add(new Hall("白银厅", 10, 12));
            halls.add(new Hall("翡翠厅", 7, 8));
            halls.add(new Hall("钻石厅", 7, 8));
            halls.add(new Hall("宝石厅", 8, 9));

            // 初始化管理器（注意顺序：先movieManager，再sessionManager，最后ticketManager）
            userManager = new UserManager();
            movieManager = new MovieManager();
            sessionManager = new SessionManager(movieManager, halls);
            ticketManager = new TicketManager(sessionManager);
        }

        public void run () {
            while (true) {
                System.out.println("欢迎使用影院管理系统！");
                System.out.println("1. 登录  2. 退出");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    login();
                } else {
                    System.out.println("再见！");
                    break;
                }
            }
        }

        private void login () {
            System.out.print("请输入用户名：");
            String username = scanner.nextLine();
            System.out.print("请输入密码：");
            String password = scanner.nextLine();
            User user = userManager.login(username, password);
            if (user == null) {
                System.out.println("用户名或密码错误！");
                return;
            }
            switch (user.getType()) {
                case "admin":
                    adminMenu((Admin) user);
                    break;
                case "manager":
                    managerMenu((Manager) user);
                    break;
                case "frontdesk":
                    frontDeskMenu((FrontDesk) user);
                    break;
            }
        }

        // 管理员菜单
        private void adminMenu (Admin admin){
            while (true) {
                System.out.println("\n管理员菜单：1. 用户管理 2. 密码管理 3. 退出登录");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    userManageMenu();
                } else if (choice == 2) {
                    passwordManageMenu(admin);
                } else {
                    break;
                }
            }
        }

        // 用户管理
        private void userManageMenu () {
            while (true) {
                System.out.println("\n用户管理：1. 列出所有用户 2. 增加用户 3. 删除用户 4. 查询用户 5. 修改用户 6. 返回");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    for (User u : userManager.getAllUsers()) {
                        System.out.println(u.getId() + " " + u.getUsername() + " " + u.getType() + " " + u.getPhone());
                    }
                } else if (choice == 2) {
                    System.out.print("输入用户ID：");
                    String id = scanner.nextLine();
                    System.out.print("输入用户名：");
                    String username = scanner.nextLine();
                    System.out.print("输入手机号：");
                    String phone = scanner.nextLine();
                    System.out.print("选择类型(1-管理员 2-经理 3-前台)：");
                    int t = Utils.getIntInput(scanner, "");
                    User user = null;
                    if (t == 1) user = new Admin(id, username, "123456", phone);
                    else if (t == 2) user = new Manager(id, username, "123456", phone);
                    else if (t == 3) user = new FrontDesk(id, username, "123456", phone);
                    if (userManager.addUser(user)) {
                        System.out.println("添加成功，初始密码123456");
                        LogManager.log("添加用户 " + username);
                    } else {
                        System.out.println("添加失败，用户名或ID已存在");
                    }
                } else if (choice == 3) {
                    System.out.print("输入要删除的用户名：");
                    String username = scanner.nextLine();
                    if (userManager.removeUser(username)) {
                        System.out.println("删除成功");
                        LogManager.log("删除用户 " + username);
                    } else {
                        System.out.println("删除失败，不能删除admin或用户不存在");
                    }
                } else if (choice == 4) {
                    System.out.print("输入用户名：");
                    String username = scanner.nextLine();
                    User u = userManager.getUserByUsername(username);
                    if (u != null) {
                        System.out.println(u.getId() + " " + u.getUsername() + " " + u.getType() + " " + u.getPhone());
                    } else {
                        System.out.println("未找到该用户");
                    }
                } // 在修改用户信息后添加：
                else if (choice == 5) {
                    System.out.print("输入用户名：");
                    String username = scanner.nextLine();
                    User u = userManager.getUserByUsername(username);
                    if (u != null) {
                        System.out.print("新手机号：");
                        String phone = scanner.nextLine();
                        u.setPhone(phone);
                        userManager.updateUser(u); // 添加这行
                        System.out.println("修改成功");
                        LogManager.log("修改用户 " + username + " 手机号");
                    } else {
                        System.out.println("未找到该用户");
                    }
                } else {
                    break;
                }
            }
        }

        // 密码管理
        private void passwordManageMenu (User user){
            while (true) {
                System.out.println("\n密码管理：1. 修改自身密码 2. 重置其他用户密码 3. 返回");
                int choice = Utils.getIntInput(scanner, "请选择：");
                // 在修改自身密码后添加：
                if (choice == 1) {
                    System.out.print("输入新密码：");
                    String pwd = scanner.nextLine();
                    user.setPassword(pwd);
                    userManager.updateUser(user); // 添加这行
                    System.out.println("修改成功");
                    LogManager.log(user.getUsername() + " 修改自身密码");
                } else if (choice == 2) {
                    System.out.print("输入要重置的用户名：");
                    String username = scanner.nextLine();
                    User u = userManager.getUserByUsername(username);
                    if (u != null && !u.getType().equals("admin")) {
                        u.setPassword("123456");
                        userManager.updateUser(u); // 添加这行
                        System.out.println("重置成功，初始密码123456");
                        LogManager.log(user.getUsername() + " 重置 " + username + " 密码");
                    } else {
                        System.out.println("不能重置admin或用户不存在");
                    }
                } else {
                    break;
                }
            }
        }

        // 经理菜单
        private void managerMenu (Manager manager){
            while (true) {
                System.out.println("\n经理菜单：1. 密码管理 2. 电影管理 3. 场次管理 4. 销售数据 5. 退出登录");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    passwordManageMenu(manager);
                } else if (choice == 2) {
                    movieManageMenu();
                } else if (choice == 3) {
                    sessionManageMenu();
                } else if (choice == 4) {
                    salesDataMenu();
                } else {
                    break;
                }
            }
        }

        // 电影管理
        private void movieManageMenu () {
            while (true) {
                System.out.println("\n电影管理：1. 列出 2. 添加 3. 删除 4. 修改 5. 查询 6. 返回");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    for (Movie m : movieManager.getAllMovies()) {
                        System.out.println(m.getName() + " " + m.getDirector() + " " + m.getActors() + " " + m.getDescription() + " " + m.getDuration() + "分钟 评分:" + m.getRating());
                    }
                } else if (choice == 2) {
                    System.out.print("片名：");
                    String name = scanner.nextLine();
                    System.out.print("导演：");
                    String director = scanner.nextLine();
                    System.out.print("主演：");
                    String actors = scanner.nextLine();
                    System.out.print("简介：");
                    String desc = scanner.nextLine();
                    int duration = Utils.getIntInput(scanner, "时长(分钟)：");
                    double rating = 0.0;
                    Movie m = new Movie(name, director, actors, desc, duration, rating);
                    if (movieManager.addMovie(m)) {
                        System.out.println("添加成功");
                        LogManager.log("添加电影 " + name);
                    } else {
                        System.out.println("添加失败，片名已存在");
                    }
                } else if (choice == 3) {
                    System.out.print("片名：");
                    String name = scanner.nextLine();
                    if (movieManager.removeMovie(name)) {
                        System.out.println("删除成功");
                        LogManager.log("删除电影 " + name);
                    } else {
                        System.out.println("删除失败，片名不存在");
                    }
                    // 在修改电影信息后添加：
                } else if (choice == 4) {
                    System.out.print("片名：");
                    String name = scanner.nextLine();
                    Movie m = movieManager.getMovieByName(name);
                    if (m != null) {
                        System.out.print("新简介：");
                        String desc = scanner.nextLine();
                        m.setDescription(desc);
                        System.out.print("新评分：");
                        double rating = Double.parseDouble(scanner.nextLine());
                        m.setRating(rating);
                        movieManager.updateMovie(m); // 添加这行
                        System.out.println("修改成功");
                        LogManager.log("修改电影 " + name);
                    } else {
                        System.out.println("未找到该电影");
                    }
                } else if (choice == 5) {
                    System.out.print("片名：");
                    String name = scanner.nextLine();
                    Movie m = movieManager.getMovieByName(name);
                    if (m != null) {
                        System.out.println(m.getName() + " " + m.getDirector() + " " + m.getActors() + " " + m.getDescription() + " " + m.getDuration() + "分钟 评分:" + m.getRating());
                    } else {
                        System.out.println("未找到该电影");
                    }
                } else {
                    break;
                }
            }
        }

        // 场次管理
        private void sessionManageMenu () {
            while (true) {
                System.out.println("\n场次管理：1. 列出 2. 添加 3. 删除 4. 返回");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    for (Session s : sessionManager.getAllSessions()) {
                        System.out.println(s.getId() + " " + s.getMovie().getName() + " " + s.getHall().getName() + " " + s.getTime() + " 票价:" + s.getPrice());
                    }
                } else if (choice == 2) {
                    System.out.print("场次ID：");
                    String id = scanner.nextLine();
                    System.out.print("片名：");
                    String mname = scanner.nextLine();
                    Movie m = movieManager.getMovieByName(mname);
                    if (m == null) {
                        System.out.println("电影不存在");
                        continue;
                    }
                    System.out.println("选择影厅：");
                    for (int i = 0; i < halls.size(); i++) {
                        System.out.println((i + 1) + ". " + halls.get(i).getName());
                    }
                    int hidx = Utils.getIntInput(scanner, "影厅编号：") - 1;
                    if (hidx < 0 || hidx >= halls.size()) {
                        System.out.println("影厅不存在");
                        continue;
                    }
                    Hall hall = halls.get(hidx);
                    System.out.print("时间(如2024-06-01 19:00)：");
                    String time = scanner.nextLine();
                    System.out.println("票价（元）：");
                    double price = Double.parseDouble(scanner.nextLine());
                    Session s = new Session(id, m, hall, time, price);
                    sessionManager.addSession(s);
                    System.out.println("添加成功");
                    LogManager.log("添加场次 " + id);
                } else if (choice == 3) {
                    System.out.print("场次ID：");
                    String id = scanner.nextLine();
                    if (sessionManager.removeSession(id)) {
                        System.out.println("删除成功");
                        LogManager.log("删除场次 " + id);
                    } else {
                        System.out.println("删除失败，场次不存在");
                    }
                } else {
                    break;
                }
            }
        }

        // 销售数据
        private void salesDataMenu () {
            System.out.println("所有场次售票情况：");
            for (Session s : sessionManager.getAllSessions()) {
                List<Ticket> ts = ticketManager.getTicketsBySession(s);
                System.out.println("场次" + s.getId() + " 电影:" + s.getMovie().getName() + " 售出:" + ts.size() + "张");
            }
        }

        // 前台菜单
        private void frontDeskMenu (FrontDesk frontDesk){
            while (true) {
                System.out.println("\n前台菜单：1. 密码管理 2. 售票 3. 退票 4. 查询场次 5. 查询座位 6. 退出登录");
                int choice = Utils.getIntInput(scanner, "请选择：");
                if (choice == 1) {
                    passwordManageMenu(frontDesk);
                } else if (choice == 2) {
                    sellTicketMenu(frontDesk);
                } else if (choice == 3) {
                    refundTicketMenu();
                } else if (choice == 4) {
                    for (Session s : sessionManager.getAllSessions()) {
                        System.out.println(s.getId() + " " + s.getMovie().getName() + " " + s.getHall().getName() + " " + s.getTime() + " 票价:" + s.getPrice());
                    }
                } else if (choice == 5) {
                    System.out.print("场次ID：");
                    String id = scanner.nextLine();
                    Session s = sessionManager.getSessionById(id);
                    if (s != null) {
                        boolean[][] seats = s.getSeats();
                        for (int i = 0; i < seats.length; i++) {
                            for (int j = 0; j < seats[i].length; j++) {
                                System.out.print(seats[i][j] ? "X " : "O ");
                            }
                            System.out.println();
                        }
                    } else {
                        System.out.println("场次不存在");
                    }
                } else {
                    break;
                }
            }
        }

        // 售票
        private void sellTicketMenu (FrontDesk frontDesk){
            System.out.print("场次ID：");
            String id = scanner.nextLine();
            Session s = sessionManager.getSessionById(id);
            if (s == null) {
                System.out.println("场次不存在");
                return;
            }
            System.out.print("排号(从1开始)：");
            int row = Utils.getIntInput(scanner, "") - 1;
            System.out.print("列号(从1开始)：");
            int col = Utils.getIntInput(scanner, "") - 1;
            if (row < 0 || row >= s.getHall().getRows() || col < 0 || col >= s.getHall().getCols()) {
                System.out.println("座位不存在");
                return;
            }
            if (s.getSeats()[row][col]) {
                System.out.println("该座已售");
                return;
            }
            Ticket t = ticketManager.sellTicket(s, row, col, frontDesk.getUsername());
            if (t != null) {
                System.out.println("售票成功，票号：" + t.getTicketId());
                LogManager.log("售票 " + t.getTicketId());
            } else {
                System.out.println("售票失败");
            }
        }

        // 退票
        private void refundTicketMenu () {
            System.out.print("票号：");
            String tid = scanner.nextLine();
            if (ticketManager.refundTicket(tid)) {
                System.out.println("退票成功");
                LogManager.log("退票 " + tid);
            } else {
                System.out.println("退票失败，票号不存在或已退");
            }
        }
    }

